package com.android.aircondition.activity;

import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.TimePicker;

import com.android.aircondition.R;
import com.android.aircondition.service.GreeService;
import com.android.aircondition.service.Timer;


public class TimerEditActivity extends BaseActivity{
	
	private GreeService service;
	private Timer timer;
	private int position;
	private TimePicker picker;
	private RadioGroup radioGroup;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timer_edit);
		
	}
	
	protected void onResume() {
		super.onResume();
		setViews();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		setTimer();
	}
	
	private void setViews(){
		
		service = new GreeService(this);
		timer   = service.getTimerPreference();
	    position = getIntent().getIntExtra("edit", 0);
		
	    radioGroup = (RadioGroup)findViewById(R.id.timerEditRadioGroup);
	    
	    
	    
		picker = (TimePicker)findViewById(R.id.timerTimePicker);
		picker.setIs24HourView(true);
		
		if(position == 0 ){
			picker.setCurrentHour(timer.getPowerOnHour());
			picker.setCurrentMinute(timer.getPowerOnMin());
			radioGroup.check(radioGroup.getChildAt(timer.getPowerOnSetting()).getId());
		}else{
			picker.setCurrentHour(timer.getPowerOffHour());
			picker.setCurrentMinute(timer.getPowerOffMin());
			radioGroup.check(radioGroup.getChildAt(timer.getPowerOffSetting()).getId());
		}
		
	}
	
	private void setTimer(){
		
		radioGroup = (RadioGroup)findViewById(R.id.timerEditRadioGroup);
		int index = radioGroup.indexOfChild(findViewById(radioGroup.getCheckedRadioButtonId()));
		int hour  = picker.getCurrentHour();
		int min   = picker.getCurrentMinute();
		
		int setting = 0;
		
		if(index == 0)
			setting = Timer.TIMES_ONLY_ONE;
		if(index == 1)
			setting = Timer.TIMES_DAILY;
		if(index == 2)
			setting = Timer.TIMES_WORKING_DAY;
		
		if(position == 0 ){
			timer.setPowerOnHour(hour);
			timer.setPowerOnMin(min);
			timer.setPowerOnSetting(setting);
		}else{
			timer.setPowerOffHour(hour);
			timer.setPowerOffMin(min);
			timer.setPowerOffSetting(setting);
		}
		
		service.setTimerPreference(timer);
		
	}
	
}
